package com.example.androidproject.app;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.androidproject.R;
import com.example.androidproject.app.adapter.ClassifyAdapter3;
import com.example.androidproject.app.classifybean.ClassifyBean;
import com.example.androidproject.movie.activity.MovieDetailActivity;
import com.example.androidproject.movie.bean.ResultBeanData;
import com.example.androidproject.novel.activity.CatalogueActivity;
import com.example.androidproject.novel.bean.NovelBean;
import com.example.androidproject.retrofit.RetrofitService;
import com.example.androidproject.utils.GlobalVariable;
import com.example.androidproject.utils.RecycleViewWork;
import com.example.androidproject.utils.ReplaceBlank;
import com.example.androidproject.utils.RequestConstant;
import com.example.androidproject.utils.ResultsConstant;
import com.example.androidproject.utils.RvBottomManager;
import com.example.androidproject.utils.Tool;
import com.example.androidproject.wallpaper.activity.WallpaperContentActivity;
import com.example.androidproject.wallpaper.bean.WallpaperBean;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * bean怎么能公用呢 数据都不一样 所以这里得通过flag判断然后再进行不同bean类选择
 */
public class ClassifyActivity3 extends Activity {
    private final String TAG = "GGSTUDY";

    private RecyclerView rv_classify;
    private int classifyFlag;
    private OkHttpClient okHttpClient;
    private RvBottomManager rvBottomManager;
    private final int limit = 15;
    private ClassifyAdapter3 classifyAdapter3;
    private LinearLayout ll_contentLoding;
    private RelativeLayout Rl_classify3;
    private ImageView back_top_btn;
    List<ResultBeanData.DataBean> movieList = new ArrayList<>();
    List<ClassifyBean.DataBean> classifyList = new ArrayList<>();
    List<NovelBean.DataBean> novelList = new ArrayList<>();
    List<WallpaperBean.DataBean> wallpaperList = new ArrayList<>();

    private int COMPLETED = 0;
    private String classify = "全部";
    private int page = 1;
    private String OptionClassify = "";
    private Retrofit retrofit;
    private int total = 0;
    private int recordPosition = -1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify3);
        Intent intent = getIntent();
        //设置顶部状态栏为透明
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        retrofit = new Retrofit.Builder()
                .baseUrl(RequestConstant.BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        classifyFlag = intent.getIntExtra("flag", 0);
        okHttpClient = new OkHttpClient();

        initView();
        getOptions();
        initPage();
        getData();
        eventListener();
    }


    // 获取分类
    private void getOptions() {
        String classifyUrl = "";
        if (classifyFlag == 1) {
            OptionClassify = "电影";
        }
        if (classifyFlag == 2) {
            OptionClassify = "小说";
        }
        if (classifyFlag == 3) {
            OptionClassify = "壁纸";
        }
        classifyUrl = RequestConstant.CLASSIFY_URL + "?" + "classify=" + OptionClassify;
        RetrofitService retrofitService = retrofit.create(RetrofitService.class);
        // 获取分类选项
        Call<ClassifyBean> optioncall = retrofitService.getOption(classifyUrl);
        optioncall.enqueue(new Callback<ClassifyBean>() {
            @Override
            public void onResponse(Call<ClassifyBean> call, Response<ClassifyBean> response) {
                if (response.isSuccessful()) {
                    ClassifyBean body = response.body();
                    if (body != null) {
                        if (body.getStatus() != 0) {
                            Toast.makeText(ClassifyActivity3.this, "请求参数有误", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        classifyList.addAll(body.getData());
                        classifyAdapter3.refreshOption(classifyList);
                    } else Log.d(TAG, "onResponse: 空的");
                } else {
                    Toast.makeText(ClassifyActivity3.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ClassifyBean> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    // 获取内容
    private void getData() {
        rvBottomManager.setLoading(true);
        lialogHandler.sendMessage(new Message());
        String url = "";
        RetrofitService retrofitService = retrofit.create(RetrofitService.class);
        if (classifyFlag == 1) {
            url = RequestConstant.MOVIE_IMG_URL + "?" + "classify=" + classify + "&" + "limit=" + limit + "&" + "page=" + page;
            retrofit2.Call<ResultBeanData> call = retrofitService.getMovie(url);
            call.enqueue(new retrofit2.Callback<ResultBeanData>() {
                @Override
                public void onResponse(retrofit2.Call<ResultBeanData> call, retrofit2.Response<ResultBeanData> response) {
                    if (response.isSuccessful()) {
                        ResultBeanData body = response.body();
                        assert body != null;
                        total = body.getTotal();
                        movieList.addAll(body.getData());
                        classifyAdapter3.insertItem(movieList);
                        ll_contentLoding.setVisibility(View.GONE);
                    } else {
                        Looper.prepare();
                        Toast.makeText(ClassifyActivity3.this, "请求失败", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        return;
                    }
                }

                @Override
                public void onFailure(retrofit2.Call<ResultBeanData> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }
        if (classifyFlag == 2) {
            OptionClassify = "小说";
            url = RequestConstant.NOVEL_URL + "?" + "classify=" + classify + "&" + "limit=" + limit + "&" + "page=" + page;
            retrofit2.Call<NovelBean> call = retrofitService.getNovel(url);
            call.enqueue(new retrofit2.Callback<NovelBean>() {
                @Override
                public void onResponse(Call<NovelBean> call, Response<NovelBean> response) {
                    if (response.isSuccessful()) {
                        NovelBean body = response.body();
                        assert body != null;
                        total = body.getTotal();
                        novelList.addAll(body.getData());
                        classifyAdapter3.insertItem(novelList);
                        ll_contentLoding.setVisibility(View.GONE);
                    } else {
                        Looper.prepare();
                        Toast.makeText(ClassifyActivity3.this, "请求失败", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        return;
                    }
                }

                @Override
                public void onFailure(Call<NovelBean> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }
        if (classifyFlag == 3) {
            url = RequestConstant.WALLPAPER_CONTENT_URL + "?classify=" + classify + "&page=" + page + "&limit=" + limit;
            Call<WallpaperBean> call = retrofitService.getWallpaper(url);
            call.enqueue(new Callback<WallpaperBean>() {
                @Override
                public void onResponse(Call<WallpaperBean> call, Response<WallpaperBean> response) {
                    if (response.isSuccessful()) {
                        WallpaperBean body = response.body();
                        assert body != null;
                        total = body.getTotal();
                        wallpaperList.addAll(body.getData());
                        classifyAdapter3.insertItem(wallpaperList);
                        ll_contentLoding.setVisibility(View.GONE);
                    } else {
                        Looper.prepare();
                        Toast.makeText(ClassifyActivity3.this, "请求失败", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        return;
                    }
                }

                @Override
                public void onFailure(Call<WallpaperBean> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }
        rvBottomManager.setLoading(false);
    }

    // 初始化布局
    private void initView() {
        rv_classify = findViewById(R.id.rv_classify3);
        Rl_classify3 = findViewById(R.id.Rl_classify3);
        back_top_btn = findViewById(R.id.back_top_btn);
        Glide.with(this).load(R.drawable.backtop).into(back_top_btn);

        ll_contentLoding = findViewById(R.id.ll_contentLoding);
        ll_contentLoding.bringToFront();

        Tool.setDiaLogCenter(ll_contentLoding, Rl_classify3);

    }

    // 初始化页面
    private void initPage() {
        if (classifyFlag == 1) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 9);
            rv_classify.setLayoutManager(gridLayoutManager);
            classifyAdapter3 = new ClassifyAdapter3(getApplicationContext(), movieList, classifyFlag, classifyList);
        }
        if (classifyFlag == 2) {
            rv_classify.setLayoutManager(new LinearLayoutManager(this));
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(0, 0, 0, 0);
            Rl_classify3.setLayoutParams(layoutParams);
            classifyAdapter3 = new ClassifyAdapter3(getApplicationContext(), novelList, classifyFlag, classifyList);
        }
        if (classifyFlag == 3) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 9);
            rv_classify.setLayoutManager(gridLayoutManager);
            classifyAdapter3 = new ClassifyAdapter3(getApplicationContext(), wallpaperList, classifyFlag, classifyList);
        }
        rv_classify.setAdapter(classifyAdapter3);

        // item点击事件 -> eventListener

        // 上拉加载
        rvBottomManager = new RvBottomManager(this, rv_classify, new RvBottomManager.Task() {
            @Override
            public void work() {
                if (total == 0) {
                } else {
                    if (limit * page >= total) {
                        rvBottomManager.setEnd(true);
                        return;
                    }
                }
                page++;
                getData();
            }
        }, back_top_btn, classifyAdapter3);
    }

    // 事件监听
    private void eventListener() {
        recordPosition = 0;
        // 全部按钮点击
        classifyAdapter3.setOnAllBtnClickListener(new ClassifyAdapter3.onAllBtnClickListener() {
            @Override
            public void onClick(TextView btn_classify_options_all1) {
                if (classifyAdapter3.classifyOptionsAdapter.mSelect == -1) {
                    return;
                }
                rvBottomManager.setEnd(false);
                classifyAdapter3.classifyOptionsAdapter.changeSelect(-1);
                btn_classify_options_all1.setBackgroundResource(R.drawable.btn_corners_css);
                page = 1;
                classify = "全部";
                if (movieList != null) {
                    int previousSize = movieList.size();
                    movieList.clear();
                    classifyAdapter3.notifyItemRangeRemoved(1, previousSize + 1);
                }
                if (novelList != null) {
                    int previousSize = novelList.size();
                    novelList.clear();
                    classifyAdapter3.notifyItemRangeRemoved(1, previousSize + 1);
                }
                classifyAdapter3.comparePosition(-1);
                getData();
            }
        });
        // 分类选项点击事件
        classifyAdapter3.setOnItemClickListenerNav(new ClassifyAdapter3.OnItemClickListenerNav() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (classifyAdapter3.clickpostion == position) {
                    return;
                }
                rvBottomManager.setEnd(false);
                page = 1;
                classify = (String) parent.getAdapter().getItem(position);
                classify = ReplaceBlank.replaceBlank(classify);
                if (movieList != null) {
                    int previousSize = movieList.size();
                    movieList.clear();
                    classifyAdapter3.notifyItemRangeRemoved(1, previousSize + 1);
                }
                if (novelList != null) {
                    if (classify.equals("其它")) classify = "其他";
                    int previousSize = novelList.size();
                    novelList.clear();
                    classifyAdapter3.notifyItemRangeRemoved(1, previousSize + 1);
                }
                if (wallpaperList != null) {
                    int previousSize = wallpaperList.size();
                    wallpaperList.clear();
                    classifyAdapter3.notifyItemRangeRemoved(1, previousSize + 1);
                }
                classifyAdapter3.comparePosition(position);
                // 点击改变颜色
                classifyAdapter3.classifyOptionsAdapter.changeSelect(position);
                getData();
            }
        });
        // 内容点击事件
        classifyAdapter3.setOnItemClickListener(new ClassifyAdapter3.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, int classifyFlag) {
                if (classifyFlag == 1) {
                    Intent intent = new Intent(getApplicationContext(), MovieDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("data", movieList.get(position));
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                if (classifyFlag == 2) {
//                    Toast.makeText(getApplicationContext(), "点击了" + position, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getApplicationContext(), CatalogueActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("data", novelList.get(position));
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                if (classifyFlag == 3) {
                    Intent intent = new Intent(getApplicationContext(), WallpaperContentActivity.class);
                    intent.putExtra("classify", wallpaperList.get(position).getClassify());
                    intent.putExtra("imgname", wallpaperList.get(position).getTitle());
                    startActivity(intent);
                }
            }
        });
        // 回到顶部按钮点击
        back_top_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rv_classify.smoothScrollToPosition(0);
            }
        });
    }

    // 加载图标handler
    public Handler lialogHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ll_contentLoding.setVisibility(View.VISIBLE);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}